package com.oneproject.infrastructure.data.mapper;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import tk.mybatis.mapper.mapperhelper.MapperHelper;

import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;

/**
 * MyBatis辅助类
 *
 * @author 马文韬
 * @date 2018/9/11
 * @version 1.0
 */
public class MyBatisHelper {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-java.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();

            SqlSession sqlSession = null;
            try {
                sqlSession = sqlSessionFactory.openSession();

                MapperHelper mapperHelper = new MapperHelper();

                mapperHelper.processConfiguration(sqlSession.getConfiguration());

                Connection conn = sqlSession.getConnection();
                reader = Resources.getResourceAsReader("oneproject.test.sql");
                ScriptRunner runner = new ScriptRunner(conn);
                runner.setLogWriter(null);
                runner.runScript(reader);
                reader.close();
            } finally {
                if (sqlSession != null) {
                    sqlSession.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}
